package com.liuyk.commonlib.update;

import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;

import com.liuyk.commonlib.help.UpdateHelp;
import com.liuyk.commonlib.network.DownloadCallBack;
import com.liuyk.commonlib.network.DownloadManager;
import com.liuyk.commonlib.utility.CommonIntentUtils;

import java.io.File;

/**
 * APP更新
 * <p>
 * Created by liuyakui on 2020-02-07.
 */
public class UpdateServer extends Service implements DownloadCallBack {

    private String mApkUrl;
    private String mVersionName;

    private MyBinder binder = new MyBinder();

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mApkUrl = intent.getStringExtra("apkUrl");
        mVersionName = intent.getStringExtra("versionName");
        DownloadManager.getInstance().download(mApkUrl, true, UpdateHelp.getApkDownloadFile(getApplicationContext(), mVersionName), this);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void downloadFail(String url, String reason) {
        UpdateNotifyManager.getInstance(getApplicationContext()).updateNotify(
                mApkUrl, mVersionName, "下载失败，点击重试");
        UpdateNotifyManager.getInstance(getApplicationContext()).clickRetry(getApplicationContext());
    }

    @Override
    public void downloading(String url, long length, long progress, int percent) {
        if (length > 0) {
            UpdateNotifyManager.getInstance(getApplicationContext()).updateProgress(
                    mApkUrl, mVersionName, (float) length, (float) progress);
        }
    }

    @Override
    public void downloadSuccess(String url, File file) {
        UpdateNotifyManager.getInstance(getApplicationContext()).updateNotify(
                mApkUrl, mVersionName, "下载完成，点击安装");
        UpdateNotifyManager.getInstance(getApplicationContext()).clickInstall(getApplicationContext());
        File renameFile = new File(UpdateHelp.getApkDir(), file.getName() + UpdateHelp.SUFFIX_APK);
        file.renameTo(renameFile);
        CommonIntentUtils.goToInstallApk(getApplicationContext(), Uri.fromFile(renameFile));
        stopSelf();
    }

    private class MyBinder extends Binder {

        public UpdateServer getService() {
            return UpdateServer.this;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
